<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>《H5移动端开发》九宫格抽奖</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        * {
            touch-action: none;
        }

        .main {
            margin-top: 20px;
            margin-left: 2px;
            margin-right: 2px;
        }

        .lottery-grid {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
        }

        .cell {
            background-color: pink;
            flex: 1;
            height: 110px;
            margin: 2px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .active {
            background-color: orange;
        }

        .btn {
            background-color: #4ACA6D;
        }
        
        .started {
            background-color: gray;
        }
    </style>
</head>

<body>
    <script src="./lottery-rate.js"></script>

    <div class="main">
        <h3>《H5移动端开发》九宫格抽奖v5</h3><br />
        <div>
            <p>
                设置所有奖品概率都不同<br>
                添加控制功能，可以控制抽中的奖品
            </p><br />
            <pre>
    /**
    * 设置所有奖品概率都不同
    *                     概率
    * 0: 奖品-苹果手机     2
    * 1: 奖品-华为手机     2 * always
    * 2: 未中-谢谢惠顾     40
    * 3: 奖品-小熊抱枕     20
    * 4: 奖品-蓝牙音响     10
    * 5: 奖品-静音风扇     10
    * 6: 奖品-格力冰箱     6
    * 7: 奖品-小米手环     10
    * 
    * 中奖范围(前闭后开)：
    * |0~2|2~4|4~44|44~64|64~74|74~84|84~90|90~100|
    * | 0 | 1 | 2  |  3  |  4  |  5  |  6  |  7   |
    */
            </pre>
        </div>
        <div class="lottery-grid">
            <div class="cell" id="item1" data-index=1>iPhone11</div>
            <div class="cell" id="item2" data-index=2>华为Mate30</div>
            <div class="cell" id="item3" data-index=3>谢谢惠顾</div>
            <div class="cell" id="item4" data-index=8>小米手环</div>
            <div class="cell btn" id="start">开始</div>
            <div class="cell" id="item5" data-index=4>小熊抱枕</div>
            <div class="cell" id="item6" data-index=7>格力冰箱</div>
            <div class="cell" id="item7" data-index=6>电风扇</div>
            <div class="cell" id="item8" data-index=5>蓝牙音响</div>
        </div>
    </div>

    <script>
        // 初始状态选中第一个
        document.querySelector(".lottery-grid > .cell:nth-child(1)").classList.add('active')

        // 商品（奖品）数组（包含中奖概率）
        let awards = [
            {
                id: 0,
                name: "iPhone11",
                rate: 2,
            },
            {
                id: 1,
                name: "华为Mate30",
                rate: 2,
            },
            {
                id: 2,
                name: "谢谢惠顾",
                rate: 40,
            },
            {
                id: 3,
                name: "小熊抱枕",
                rate: 20,
            },
            {
                id: 4,
                name: "蓝牙音响",
                rate: 10,
            },
            {
                id: 5,
                name: "静音风扇",
                rate: 10,
            },
            {
                id: 6,
                name: "格力冰箱",
                rate: 6,
            },
            {
                id: 7,
                name: "小米手环",
                rate: 10,
            },
        ]

        // let rates = [2, 2, 40, 20, 10, 10, 6, 10]

        /**
         * 设置所有奖品概率都不同
         *                     概率
         * 0: 奖品-华为手机     2
         * 1: 奖品-苹果手机     2
         * 2: 未中-谢谢惠顾     40
         * 3: 奖品-小熊抱枕     20
         * 4: 奖品-蓝牙音响     10
         * 5: 奖品-静音风扇     10
         * 6: 奖品-格力冰箱     6
         * 7: 奖品-小米手环     10
         * 
         * 中奖范围(前闭后开)：
         * |0~2|2~4|4~44|44~64|64~74|74~84|84~90|90~100|
         * | 0 | 1 | 2  |  3  |  4  |  5  |  6  |  7   |
         */

        const speedUpAt = 4     // 从第4个开始逐渐加速
        const minMove = 30      // 最少滚动30+下
        const slowDownAt = -10  // 距离结束还剩10次滚动时逐渐减速

        let items = document.querySelectorAll(".lottery-grid > .cell:not(.btn)")
        // 获取排序为[顺时针滚动顺序]的元素数组
        let sortedItems = Array.from(items).sort(function (a, b) {
            let indexA = a.getAttribute("data-index")
            let indexB = b.getAttribute("data-index")
            return indexA < indexB ? -1 : 1
        })

        let moveCount = 0
        let adding = 0
        let interval = null
        let time = 600
        let started = false

        let start = document.getElementById("start")
        // 点击[开始]，开始抽奖滚动
        start.addEventListener("click", function () {
            if (started) {
                return
            }
            started = true
            start.classList.add('started')
            
            setActiveItem(0)

            // 按照指定概率，获取中奖商品
            let rates = awards.map(item=>{
                return item.rate
            })
            moveCount = lottery(rates, 1)   // 将获奖指定为[1: 华为Mate30]
            console.log(`本次将滚动次数为：${moveCount}`)

            interval = setInterval(() => {
                moving()
            }, time);
        })

        // 滚动处理
        function moving() {
            clearInterval(interval)
            let current = 0

            // stop
            if (adding > moveCount) {
                start.classList.remove('started')
                started = false
                adding = 0
                current = moveCount % items.length
                let result = `[抽中奖品] ${current+1}: ${sortedItems[current].innerText}`
                console.log(result)
                alert(result)
                return
            }

            current = adding % items.length
            setActiveItem(current)

            // 即将结束滚动时，减速
            if (adding > moveCount + slowDownAt) {
                if (time < 800)(time += 60)
                interval = setInterval(() => {
                    moving()
                }, time);
            }
            // 滚动超过指定次数后开始加速
            else if (adding > speedUpAt) {
                if (time > 180)(time -= 60)
                interval = setInterval(() => {
                    moving()
                }, time);
            }
            // 开始滚动时
            else {
                time -= 50
                interval = setInterval(() => {
                    moving()
                }, time);
            }
            adding += 1
        }

        // 设置当前选中项
        function setActiveItem(activeIndex) {
            items.forEach(item => {
                item.classList.remove('active')
            })
            sortedItems[activeIndex].classList.add('active')
        }
    </script>
</body>

</html>